<template>
  <div>
    <el-card style="width: 100%; height: 100%">
      <el-breadcrumb :separator-icon="ArrowRight">
        <el-breadcrumb-item :to="{ path: '/' }">物料管理</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: '/ProductList' }">产品管理</el-breadcrumb-item>
        <el-breadcrumb-item>新增产品</el-breadcrumb-item>
      </el-breadcrumb>
    </el-card>
    <el-card style="width: 100%; height: 100%; margin-top: 5px">
      <h2 style="margin: 0 0 20px 0">新增产品</h2>
      
      <!-- 标签页 -->
      <el-tabs v-model="activeTab">
        <el-tab-pane label="基础信息" name="basic">
          <!-- 表单 -->
          <el-form
            ref="formRef"
            :model="formModel"
            :rules="rules"
            label-width="120px"
            style="margin-top: 20px"
          >
            <el-row :gutter="24">
              <!-- 左列 -->
              <el-col :span="12">
                <el-form-item label="产品编号" prop="productCode" required>
                  <el-input
                    v-model="formModel.productCode"
                    placeholder="请输入"
                    clearable
                  />
                </el-form-item>
                
                <el-form-item label="规格型号">
                  <el-input
                    v-model="formModel.specification"
                    placeholder="请输入"
                    clearable
                  />
                </el-form-item>
                
                <el-form-item label="产品类型" prop="productType" required>
                  <el-select
                    v-model="formModel.productType"
                    placeholder="请选择产品类型"
                    style="width: 100%"
                    clearable
                  >
                    <el-option
                      v-for="item in productTypeOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
                
                <el-form-item label="产品分类">
                  <el-select
                    v-model="formModel.productCategory"
                    placeholder="请选择产品分类"
                    style="width: 100%"
                    clearable
                  >
                    <el-option
                      v-for="item in productCategoryOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
                
                <el-form-item label="有效期期">
                  <div style="display: flex; align-items: center; gap: 8px">
                    <el-input-number
                      v-model="formModel.productdays"
                      :min="0"
                      placeholder="请输入"
                      style="flex: 1"
                    />
                    <el-select
                      v-model="validityPeriodUnit"
                      style="width: 80px"
                    >
                      <el-option label="天" value="天" />
                    </el-select>
                    <el-checkbox v-model="validityPeriodEnabled" />
                  </div>
                </el-form-item>
                
                <el-form-item label="库存上限">
                  <el-input-number
                    v-model="formModel.productupper"
                    :min="0"
                    placeholder="请输入"
                    style="width: 100%"
                  />
                </el-form-item>
                
                <el-form-item label="采购价格">
                  <el-input-number
                    v-model="formModel.productmoney"
                    :min="0"
                    :precision="2"
                    placeholder="请输入"
                    style="width: 100%"
                  />
                </el-form-item>
                
                <el-form-item label="备注">
                  <el-input
                    v-model="formModel.productdes"
                    type="textarea"
                    :rows="4"
                    placeholder="请输入"
                    maxlength="200"
                    show-word-limit
                  />
                </el-form-item>
              </el-col>
              
              <!-- 右列 -->
              <el-col :span="12">
                <el-form-item label="系统编号">
                  <el-switch v-model="formModel.systemCodeEnabled" />
                </el-form-item>
                
                <el-form-item label="产品名称" prop="productName" required>
                  <el-input
                    v-model="formModel.productName"
                    placeholder="请输入"
                    clearable
                  />
                </el-form-item>
                
                <el-form-item label="单位">
                  <el-select
                    v-model="formModel.unit"
                    placeholder="请选择单位"
                    style="width: 100%"
                    clearable
                  >
                    <el-option
                      v-for="item in unitOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
                
                <el-form-item label="产品属性">
                  <el-select
                    v-model="formModel.productAttribute"
                    placeholder="请选择产品属性"
                    style="width: 100%"
                    clearable
                  >
                    <el-option
                      v-for="item in productAttributeOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item label="状态">
                  <el-radio-group v-model="formModel.productstate">
                    <el-radio :label="true">启用</el-radio>
                    <el-radio :label="false">禁用</el-radio>
                  </el-radio-group>
                </el-form-item>
                
                <el-form-item label="报警天数">
                  <div style="display: flex; align-items: center; gap: 8px">
                    <span>提前</span>
                    <el-input-number
                      v-model="formModel.productstopdays"
                      :min="0"
                      placeholder="请输入"
                      style="flex: 1"
                    />
                    <span>天报警</span>
                  </div>
                </el-form-item>
                
                <el-form-item label="库存下限">
                  <el-input-number
                    v-model="formModel.productdown"
                    :min="0"
                    placeholder="请输入"
                    style="width: 100%"
                  />
                </el-form-item>
                
                <el-form-item label="销售价格">
                  <el-input-number
                    v-model="formModel.salesPrice"
                    :min="0"
                    :precision="2"
                    placeholder="请输入"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          
          <!-- 图片上传区域 -->
          <el-divider />
          <div style="margin: 20px 0">
            <h3 style="margin: 0 0 15px 0">图片</h3>
            <div style="display: flex; gap: 15px; align-items: flex-start">
              <el-button type="primary" @click="triggerImageUpload">上传图片</el-button>
              <input
                ref="imageInputRef"
                type="file"
                accept="image/*"
                style="display: none"
                @change="handleImageChange"
              />
              <div
                v-if="imagePreview"
                style="position: relative; display: inline-block"
              >
                <el-image
                  :src="imagePreview"
                  style="width: 150px; height: 150px; border: 1px dashed #dcdfe6; border-radius: 4px"
                  fit="cover"
                />
                <el-button
                  type="danger"
                  size="small"
                  circle
                  style="position: absolute; top: -10px; right: -10px"
                  @click="removeImage"
                >
                  <el-icon><Close /></el-icon>
                </el-button>
              </div>
              <div
                v-else
                style="
                  width: 150px;
                  height: 150px;
                  border: 1px dashed #dcdfe6;
                  border-radius: 4px;
                  display: flex;
                  flex-direction: column;
                  align-items: center;
                  justify-content: center;
                  cursor: pointer;
                  color: #909399;
                "
                @click="triggerImageUpload"
              >
                <el-icon style="font-size: 40px; margin-bottom: 8px"><Plus /></el-icon>
                <span>上传图片</span>
              </div>
            </div>
          </div>
          
          <!-- 附件上传区域 -->
          <el-divider />
          <div style="margin: 20px 0">
            <h3 style="margin: 0 0 15px 0">附件</h3>
            <el-upload
              ref="fileUploadRef"
              :auto-upload="false"
              :on-change="handleFileChange"
              :on-remove="handleFileRemove"
              :file-list="fileList"
              drag
              style="width: 100%"
            >
              <el-icon class="el-icon--upload"><upload-filled /></el-icon>
              <div class="el-upload__text">
                点击或者拖动文件到虚线框内上传
              </div>
              <template #tip>
                <div class="el-upload__tip">
                  支持 docx, xls, PDF, rar, zip, PNG, JPG 等类型的文件
                </div>
              </template>
            </el-upload>
          </div>
          
          <!-- 底部按钮 -->
          <div style="margin-top: 30px; text-align: right">  
            <el-button @click="handleClose">关闭</el-button>
            <el-button type="primary" @click="handleSubmit" :loading="submitting">确定</el-button>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { ArrowRight, Close, Plus, UploadFilled } from "@element-plus/icons-vue";
import https from "@/Http/http";
import { onMounted, reactive, ref } from "vue";
import { ElMessage, type FormInstance, type FormRules, type UploadFile } from "element-plus";
import { useRouter } from "vue-router";

const router = useRouter();

// 写库 API 使用统一的 https.Writes 实例

// 表单引用
const formRef = ref<FormInstance>();
const imageInputRef = ref<HTMLInputElement>();
const fileUploadRef = ref();
const submitting = ref(false);
const activeTab = ref("basic");

// 表单数据
const formModel = reactive({
  productCode: "",
  productName: "",
  specification: "",
  unit: "",
  productType: null as number | null,
  productAttribute: null as number | null,
  productCategory: null as number | null,
  productstate: true,
  productdays: 0,
  productstopdays: 0,
  productupper: 0,
  productdown: 0,
  productmoney: 0,
  productdes: "",
  productphoto: "",
  productfile: "",
  systemCodeEnabled: false,
  salesPrice: 0,
  bomid: null as number | null,
  process_routecode: "",
});

// 有效期单位
const validityPeriodUnit = ref("天");
const validityPeriodEnabled = ref(false);

// 图片预览
const imagePreview = ref("");
const uploadedImageUrl = ref("");

// 文件列表
const fileList = ref<UploadFile[]>([]);
const uploadedFileUrl = ref("");

// 选项数据
const productTypeOptions = [
  { label: "类型一", value: 1 },
  { label: "类型二", value: 2 },
  { label: "类型三", value: 3 },
];

const productAttributeOptions = [
  { label: "自制", value: 1 },
  { label: "外购", value: 2 },
];

const productCategoryOptions = [
  { label: "分类一", value: 1 },
  { label: "分类二", value: 2 },
  { label: "分类三", value: 3 },
];

const unitOptions = [
  { label: "个", value: "个" },
  { label: "件", value: "件" },
  { label: "箱", value: "箱" },
  { label: "包", value: "包" },
  { label: "kg", value: "kg" },
  { label: "g", value: "g" },
];

// 表单验证规则
const rules = reactive<FormRules>({
  productCode: [{ required: true, message: "产品编号不可为空", trigger: "blur" }],
  productName: [{ required: true, message: "产品名称不可为空", trigger: "blur" }],
  productType: [{ required: true, message: "请选择产品类型", trigger: "change" }],
});

const bomOptions = ref<Array<{ label: string; value: number }>>([]);
const processRouteOptions = ref<Array<{ label: string; value: string }>>([]);
const bomLoading = ref(false);
const processRouteLoading = ref(false);

const fetchBomOptions = async () => {
  bomLoading.value = true;
  try {
    const params = { pageindex: 1, pagesize: 1000 };
    const { data } = await https.Reads.get("/Bom/BomGetList", { params });
    if (data?.code === 1 || data?.Code === 1) {
      const list = data.data || data.Data || [];
      bomOptions.value = list.map((item: any) => ({
        label: item.bomname
          ? `${item.bomname}${item.bomcode ? `（${item.bomcode}）` : ""}`
          : item.bomcode,
        value: item.id,
      }));
    }
  } catch (error) {
    console.error("获取BOM列表失败:", error);
  } finally {
    bomLoading.value = false;
  }
};

const fetchProcessRouteOptions = async () => {
  processRouteLoading.value = true;
  try {
    const params = { pageindex: 1, pagesize: 500, process_routenameorcode: "" };
    const { data } = await https.Reads.get("/AManufacturing_process/AProcess_routeShow", {
      params,
    });
    if (data?.code === 1 || data?.Code === 1) {
      const list = data.data || data.Data || [];
      processRouteOptions.value = list.map((item: any) => ({
        label: item.process_routename
          ? `${item.process_routename}${item.process_routecode ? `（${item.process_routecode}）` : ""}`
          : item.process_routecode,
        value: item.process_routecode,
      }));
    }
  } catch (error) {
    console.error("获取工艺路线失败:", error);
  } finally {
    processRouteLoading.value = false;
  }
};

// 触发图片上传
const triggerImageUpload = () => {
  imageInputRef.value?.click();
};

// 处理图片选择
const handleImageChange = async (event: Event) => {
  const target = event.target as HTMLInputElement;
  const file = target.files?.[0];
  if (!file) return;

  // 验证文件类型
  if (!file.type.startsWith("image/")) {
    ElMessage.error("请选择图片文件");
    return;
  }

  // 验证文件大小（例如：5MB）
  if (file.size > 5 * 1024 * 1024) {
    ElMessage.error("图片大小不能超过5MB");
    return;
  }

  // 预览图片
  const reader = new FileReader();
  reader.onload = (e) => {
    imagePreview.value = e.target?.result as string;
  };
  reader.readAsDataURL(file);

  // 上传图片
  try {
    const formData = new FormData();
    formData.append("file", file);

    const response = await https.Writes.post(`/Product/UploadImgs`, formData, {
      headers: {
        "Content-Type": "multipart/form-data",
      },
    });

    if (response.data) {
      uploadedImageUrl.value = response.data;
      formModel.productphoto = response.data;
      ElMessage.success("图片上传成功");
    }
  } catch (error) {
    console.error("图片上传失败:", error);
    ElMessage.error("图片上传失败，请稍后再试");
    imagePreview.value = "";
  }
};

// 移除图片
const removeImage = () => {
  imagePreview.value = "";
  uploadedImageUrl.value = "";
  formModel.productphoto = "";
  if (imageInputRef.value) {
    imageInputRef.value.value = "";
  }
};

// 处理文件变化
const handleFileChange = async (file: UploadFile) => {
  const rawFile = file.raw;
  if (!rawFile) return;

  // 验证文件类型
  const allowedTypes = [
    "application/vnd.openxmlformats-officedocument.wordprocessingml.document", // docx
    "application/vnd.ms-excel", // xls
    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", // xlsx
    "application/pdf", // PDF
    "application/x-rar-compressed", // rar
    "application/zip", // zip
    "image/png", // PNG
    "image/jpeg", // JPG
  ];
  
  const fileExtension = rawFile.name.split(".").pop()?.toLowerCase();
  const allowedExtensions = ["docx", "xls", "xlsx", "pdf", "rar", "zip", "png", "jpg", "jpeg"];

  if (!allowedExtensions.includes(fileExtension || "")) {
    ElMessage.error("不支持的文件类型，请上传 docx, xls, PDF, rar, zip, PNG, JPG 等类型的文件");
    fileUploadRef.value?.handleRemove(file);
    return;
  }

  // 上传文件
  try {
    const formData = new FormData();
    formData.append("file", rawFile);

    const response = await https.Writes.post(`/Product/UploadImgs`, formData, {
      headers: {
        "Content-Type": "multipart/form-data",
      },
    });

    if (response.data) {
      uploadedFileUrl.value = response.data;
      formModel.productfile = response.data;
      ElMessage.success("文件上传成功");
    }
  } catch (error) {
    console.error("文件上传失败:", error);
    ElMessage.error("文件上传失败，请稍后再试");
    fileUploadRef.value?.handleRemove(file);
  }
};

// 处理文件移除
const handleFileRemove = () => {
  uploadedFileUrl.value = "";
  formModel.productfile = "";
};

onMounted(() => {
  fetchBomOptions();
  fetchProcessRouteOptions();
});

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;

  await formRef.value.validate(async (valid) => {
    if (!valid) {
      return;
    }

    submitting.value = true;

    try {
      // 构建请求数据
      const requestData: Record<string, any> = {
        productcard: formModel.productCode,
        productname: formModel.productName,
        productmodelsame: formModel.specification,
        productunit: formModel.unit || "",
        producttypeid: formModel.productType || 0,
        productattributeid: formModel.productAttribute || 0,
        productclassificationid: formModel.productCategory || 0,
        productstate: formModel.productstate,
        productdays: formModel.productdays,
        productstopdays: formModel.productstopdays,
        productupper: formModel.productupper,
        productdown: formModel.productdown,
        productmoney: formModel.productmoney,
        productdes: formModel.productdes || "",
        productphoto: formModel.productphoto || "",
        productfile: formModel.productfile || "",
      };

      if (formModel.bomid !== null && formModel.bomid !== undefined) {
        requestData.bomid = formModel.bomid;
      }

      if (formModel.process_routecode) {
        requestData.process_routecode = formModel.process_routecode;
      }

      const response = await https.Writes.post(
        `/Product/ProductAdd`,
        requestData
      );

      if (response.data.code === 1) {
        ElMessage.success(response.data.msg || "新增产品成功");
        // 跳转回产品列表
        router.push("/ProductList");
      } else {
        ElMessage.error(response.data.msg || "新增产品失败");
      }
    } catch (error) {
      console.error("新增产品失败:", error);
      ElMessage.error("请求失败，请稍后再试");
    } finally {
      submitting.value = false;
    }
  });
};

// 关闭
const handleClose = () => {
  router.push("/ProductList");
};
</script>

<style scoped>
.el-upload__tip {
  color: #606266;
  font-size: 12px;
  margin-top: 7px;
}
</style>

